import type { HttpContext } from '@adonisjs/core/http'
import db from '@adonisjs/lucid/services/db'
import vine from '@vinejs/vine'

export default class ReportsController {
  async inOutStock(ctx: HttpContext) {
    const dateRangeValidate = vine.compile(
      vine.object({
        startTime: vine.date(),
        endTime: vine.date(),
      })
    )

    const { startTime, endTime } = await ctx.request.validateUsing(dateRangeValidate)

    const res = await db.rawQuery('select * from in_out_report(:startTime,:endTime)', {
      startTime,
      endTime,
    })

    return res.rows
  }

  async stock(ctx: HttpContext) {
    const dateRangeValidate = vine.compile(
      vine.object({
        date: vine.date(),
        goodsId: vine.number().optional(),
        warehouseId: vine.number().optional(),
        returnType: vine.number().optional(),
      })
    )

    const {
      date,
      goodsId = null,
      warehouseId = null,
      returnType = 1,
    } = await ctx.request.validateUsing(dateRangeValidate)

    const res = await db.rawQuery(
      'select * from stock_report(:date,:goodsId,:warehouseId,:returnType)',
      {
        date,
        goodsId,
        warehouseId,
        returnType,
      }
    )

    return res.rows
  }
}
